package org.example;

import java.util.LinkedList;

/**
 * 逆波兰式表达式求值
 * 逆波兰式也叫后缀式，即运算符写在后面
 *
 * 题目假设：
 * 数字都视为整数
 * 数字和运算符个数给定正确，不会有除零的情况发生
 */
public class E02Leetcode150 {

    public int evelRPN (String[] tokens) {
        LinkedList<Integer> linkedList = new LinkedList<>();
        for (String token : tokens) {
            switch (token) {
                case "+" -> {
                    Integer a = linkedList.pop();
                    Integer b = linkedList.pop();
                    linkedList.push(b + a);
                }
                case "-" -> {
                    Integer a = linkedList.pop();
                    Integer b = linkedList.pop();
                    linkedList.push(b - a);
                }
                case "*" -> {
                    Integer a = linkedList.pop();
                    Integer b = linkedList.pop();
                    linkedList.push(b * a);
                }
                case "/" -> {
                    Integer a = linkedList.pop();
                    Integer b = linkedList.pop();
                    linkedList.push(b / a);
                }
                default -> linkedList.push(Integer.parseInt(token));
            }
        }
        return linkedList.pop();
    }

    public static void main(String[] args) {
        String[] tokens = new String[]{"1", "2", "3", "+", "*"};
        E02Leetcode150 leetcode = new E02Leetcode150();
        System.out.println(leetcode.evelRPN(tokens));
    }
}
